package com.css.fxfzcpxx.base.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzcpxx.base.user.repository.CertificationRepository;
import com.css.fxfzcpxx.base.user.repository.UserRepository;
import com.css.fxfzcpxx.base.user.repository.entity.CertificationEntity;
import com.css.fxfzcpxx.base.user.repository.entity.UserEntity;
import com.css.fxfzcpxx.base.user.repository.impl.UserNativeRepository;
import com.css.fxfzcpxx.base.user.service.UserService;
import com.css.fxfzcpxx.base.user.viewobjects.UserBaseInfoVO;
import com.css.fxfzcpxx.base.user.viewobjects.UserQueryParams;
import com.css.fxfzcpxx.base.user.viewobjects.UserVO;
import com.css.fxfzcpxx.config.property.FxfzConfig;
import com.css.fxfzcpxx.constants.CertificationLockedEnum;
import com.css.fxfzcpxx.constants.YNEnum;
import com.css.fxfzcpxx.login.security.SecretKeyRuleService;
import com.css.fxfzcpxx.util.*;
import com.css.fxfzcpxx.web.PlatformSessionContext;
import com.css.fxfzcpxx.zcpt.sys.entity.SUser;
import com.css.fxfzcpxx.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    FxfzConfig fxfzConfig;
    @Autowired
    UserRepository userRepository;
    @Autowired
    SecretKeyRuleService secretKeyRuleService;
    @Autowired
    CertificationRepository certificationRepository;
    @Autowired
    private UserNativeRepository userNativeRepository ;
    @Autowired
    private SUserService sUserServicel;
    @Override
    @Transactional
    public UserVO saveUser(UserVO userVO) throws Exception {
        UserEntity user = userVO.getUser();
        //检查用户名是否重复
        UserEntity entity = userRepository.findByUserCode(user.getUserCode());
        if(PlatformObjectUtils.isNotEmpty(entity)){
            throw new Exception("用户名已存在，请重新输入！");
        }

        String uuid = UUIDGenerator.getUUID();
        user.setUserId(uuid);
        user.setIsValid(YNEnum.Y.toString());
        user.setCreateDate(PlatformDateUtils.getCurrentTimestamp());
        UserEntity resultUser = userRepository.save(user);
        //创建用户登录校验实体
        CertificationEntity certificationEntity = new CertificationEntity();
        certificationEntity.setUserId(uuid);
        certificationEntity.setLocked(CertificationLockedEnum.NORMAL.getCode());
        //取默认密码
        String defaultPwd = fxfzConfig.getDefaultPwd();
        //加盐，加密
        certificationEntity = secretKeyRuleService.encryption(certificationEntity, defaultPwd);

        certificationEntity.setPwdUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        certificationRepository.save(certificationEntity);
        return new UserVO(resultUser);
    }

    @Override
    public JSONObject getAllUserByParams(UserQueryParams queryParams) {
        return PlatformPageUtils.formatPageData(userRepository.getAllUserByParams(queryParams));
    }

    @Override
    public UserBaseInfoVO getUser(String userId) {

        Map<String, Object> userBaseInfoVOByUserId = userRepository.findUserBaseInfoVOByUserId(userId);
        if(PlatformObjectUtils.isEmpty(userBaseInfoVOByUserId)){
            String sUser = sUserServicel.getSUser(userId);
            UserBaseInfoVO userBaseInfoVO= JSON.parseObject(sUser,UserBaseInfoVO.class);
            userBaseInfoVO.setPeopleGroup("地震行业");
            return userBaseInfoVO;
        }
        UserBaseInfoVO userBaseInfoVO= (UserBaseInfoVO) PlatformBeanUtils.copyProperties(userBaseInfoVOByUserId, UserBaseInfoVO.class);

        if (!ObjectUtils.isEmpty(userBaseInfoVO.getLocked())) {
            userBaseInfoVO.setLocked(CertificationLockedEnum.getCertificationLockedEnumMap(userBaseInfoVO.getLocked()).getName());
        }
        return userBaseInfoVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserVO updateUser(UserVO userVO) {
        UserEntity user = userVO.getUser();
        user.setIsValid(YNEnum.Y.toString());
        user.setUpdateDate(PlatformDateUtils.getCurrentTimestamp());
        UserEntity resultUser = userRepository.save(user);
        return new UserVO(resultUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(List<String> userIds) {
        String currUserId = PlatformSessionUtils.getUserId();
        Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
        userRepository.deleteUsers(userIds, currUserId, currentTimestamp);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserEntity registerUser(UserEntity userEntity) throws Exception {
        //检查用户名是否重复
        UserEntity entity = userNativeRepository.findByUserCode(userEntity.getUserCode());
        if(PlatformObjectUtils.isNotEmpty(entity)){
            throw new Exception("用户名已存在，请重新输入！");
        }else if(PlatformObjectUtils.isNotEmpty(userNativeRepository.findByMobilePhone(userEntity.getMobilePhone()))){
            throw new Exception("该手机号已注册！");
        }
        String uuid = UUIDGenerator.getUUID();
        userEntity.setUserId(uuid);
        userEntity.setIsValid(YNEnum.Y.toString());
        userEntity.setCreateDate(PlatformDateUtils.getCurrentTimestamp());
        userNativeRepository.save(userEntity);
        //创建用户登录校验实体
        CertificationEntity certificationEntity = new CertificationEntity();
        certificationEntity.setUserId(uuid);
        certificationEntity.setLocked(CertificationLockedEnum.NORMAL.getCode());
        String pwd = userEntity.getPassword();
        //加盐，加密
        certificationEntity = secretKeyRuleService.encryption(certificationEntity, pwd);
        certificationEntity.setUpdateUser(uuid);
        certificationEntity.setPwdUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        certificationRepository.save(certificationEntity);
        return  userEntity;
    }

    @Override
    public String getUserIdentity() {
        String userIdentity="";
        String userId = PlatformSessionContext.getUserID();
        userId="80cd530287e54c6788925adf2dfc9da1";
        userIdentity=userRepository.findPeopleGroupByUserId(userId);
        if(PlatformObjectUtils.isEmpty(userIdentity)){
            String user = sUserServicel.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            if(PlatformObjectUtils.isNotEmpty(sUser)){
                userIdentity="地震行业";
            }
        }
        return userIdentity;
    }
}
